#!/usr/bin/env node
import express from 'express'
import cors from 'cors'
import OpenAI from 'openai'

const app = express()
app.use(cors())
app.use(express.json())

const port = process.env.PORT || 3000
const apiKey = process.env.OPENAI_API_KEY
if (!apiKey) console.warn('Warning: OPENAI_API_KEY is not set. Set it before running the server.')

const client = new OpenAI({ apiKey })

app.post('/api/chat', async (req, res) => {
  try {
    const { message, model } = req.body || {}
    if (!message) return res.status(400).json({ error: 'missing message' })

    const modelName = model || process.env.OPENAI_MODEL || 'gpt-4o-mini'

    const completion = await client.chat.completions.create({
      model: modelName,
      messages: [{ role: 'user', content: String(message) }],
    })

    const text = completion?.choices?.[0]?.message?.content ?? ''
    return res.json({ text })
  } catch (err) {
    console.error('proxy /api/chat error:', err)
    return res.status(500).json({ error: String(err) })
  }
})

app.listen(port, () => console.log(`Proxy listening on http://localhost:${port}`))
